
from feature import Feature, FeatureParser, registerFeatureParserClass
from wigglefeature import WiggleFeatureParser

class FragmentCoverageFeature(Feature):

    def getDetails(self):
        cols = self.content.strip().split("\t")
        self.reads = int(cols[0])
        self.genomic = cols[1]
        if len(cols)<=2:
            self.snp = False
            return self
        self.snp = True
        coverageInfoField = cols[2]
        # T=8,C=1
        coverageInfoBases = coverageInfoField.split(",")
        
        self.cts = {}
        self.info = {}
        for baseStr in coverageInfoBases:
            (base, cts) = tuple(baseStr.split("="))
            cts = int(cts)
            self.cts[base] = cts
        return self

    def getCountsAsString(self):
        details = self.getDetails()
        if not details.snp:
            cts = {"A":0, "C":0, "G":0, "T":0}
            cts[details.genomic] = details.reads
        else:
            cts = {}
            for base in ["A", "C", "G", "T"]:
                cts[base] = details.cts.get(base, 0)
        return "%d/%d/%d/%d" % (cts["A"], cts["C"], cts["G"], cts["T"])
        
class FragmentCoverageFeatureParser(WiggleFeatureParser):

    def parse(self, line):
        feature = WiggleFeatureParser.parse(self, line)
        if feature == None: return None
        return FragmentCoverageFeature(feature.chr, feature.spos, feature.epos, feature.content)

registerFeatureParserClass("fragment_coverage_summary", FragmentCoverageFeatureParser)
